package com.liqi.display.schedule;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.liqi.display.common.Constants;
import com.liqi.display.entity.returnType.TopEightTask;
import com.liqi.display.entity.returnType.WaitAndGetTimeForArea;
import com.liqi.display.entity.returnType.WaitAndGetTotal;
import com.liqi.display.enums.RegionEnum;
import com.liqi.display.service.*;
import com.liqi.display.service.impl.UpProAcceptServiceImpl;
import com.liqi.display.utils.CalculateUtil;
import com.liqi.display.utils.DateUtil;
import com.liqi.display.utils.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 定时任务类
 */
@Component
@Configurable
public class ScheduledTasks {

    private static Logger logger= LoggerFactory.getLogger(ScheduledTasks.class);

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    ITblTakeNumberService takeNumberService; //取号

    @Autowired
    ITblOArchiveService oArchiveService; //预约

    @Autowired
    private UpProAcceptServiceImpl upProAcceptService;//办理

    @Autowired
    IUpProEvalService upProEvalService;//满意度

    @Autowired
    private ITblAnnounceNumberService announceNumberService;

    @Autowired
    private ITblHandoutarchiveService iTblHandoutarchiveService;

    @Autowired
    IUpProResultService upProResultService;

    @Autowired
    IUpProReceiveService upProReceiveService;
    @Autowired
    IStatisticsService statisticsService;
    
    @Autowired
    private ISystemParamService systemParamService;
    
    @Value("${param.wait.time}")
	private String waitTime;
    
    @Value("${param.access.time}")
	private String accessTime;

    //0.当天业务量统计分析
    public void dayRunBatchByCron(){
        try {
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            SimpleDateFormat fmat=new SimpleDateFormat("yyyy-MM-dd");
            String start = sdf.format(DateUtil.getDay());
            String end = sdf.format(DateUtil.getCurrentDay());
            String dayEnd = fmat.format(DateUtil.getDay()) + " 23:59:59";
            int dayOrderTotal = statisticsService.getOrderDayTotal(start,dayEnd);//获取当天的预约数
            int dayNumTotal = statisticsService.getNumDayTotal(start,end);//获取当天的取号总数
            int currentDayTotal=statisticsService.getXCNumDayTotal(start,end);//获取当天的现场号
            int webchatDayTotal=statisticsService.getWXNumDayTotal(start,end);//获取当天的微信号
            int orderDayTotal=statisticsService.getYYNumDayTotal(start,end);//获取当天预约取号数
            int receiveDayTotal = statisticsService.getTotalDeal(start,end);//当天收件量
            int totalSendDay=statisticsService.getTotalSend(start,end);//获取当天发证量号
            //存入redis
            redisUtil.hashSet(DateUtil.format(new Date(),Constants.DAY),Constants.NUM_DAY_TATAL,dayNumTotal);
            redisUtil.hashSet(DateUtil.format(new Date(),Constants.DAY),Constants.ORDER_DAY_TATAL,dayOrderTotal);
            redisUtil.hashSet(DateUtil.format(new Date(),Constants.DAY),Constants.NUM_XC_DAY_TATAL,currentDayTotal);
            redisUtil.hashSet(DateUtil.format(new Date(),Constants.DAY),Constants.NUM_YY_DAY_TATAL,orderDayTotal);
            redisUtil.hashSet(DateUtil.format(new Date(),Constants.DAY),Constants.NUM_SEND_DAY_TATAL,totalSendDay);
            redisUtil.hashSet(DateUtil.format(new Date(),Constants.DAY),Constants.NUM_RECEIVE_DAY_TATAL,receiveDayTotal);
            redisUtil.hashSet(DateUtil.format(new Date(),Constants.DAY),Constants.NUM_WX_DAY_TATAL,webchatDayTotal);//天预约数
        }catch (Exception e) {
            logger.info("定时获取天数据异常:{}",e);
            //参考现场初始化公司本地展示数据
            //获取当天的取号总数
            redisUtil.hashSet(DateUtil.format(new Date(),Constants.DAY),Constants.NUM_DAY_TATAL,49);
            //预约数据
            redisUtil.hashSet(DateUtil.format(new Date(),Constants.DAY),Constants.ORDER_DAY_TATAL,86);
            //当天收件量
            redisUtil.hashSet(DateUtil.format(new Date(),Constants.DAY),Constants.NUM_RECEIVE_DAY_TATAL,46);
            //获取日现场取号数
            redisUtil.hashSet(DateUtil.format(new Date(),Constants.DAY),Constants.NUM_XC_DAY_TATAL,43);
            //预约取号数
            redisUtil.hashSet(DateUtil.format(new Date(),Constants.DAY),Constants.NUM_YY_DAY_TATAL,60);//当天预约数
            //发件数
            redisUtil.hashSet(DateUtil.format(new Date(),Constants.DAY),Constants.NUM_SEND_DAY_TATAL,23);
            //微信取号(手机取号)
            redisUtil.hashSet(DateUtil.format(new Date(),Constants.DAY),Constants.NUM_WX_DAY_TATAL,0);//当天微信取号数
        }
    }

    /**
     * 1.获取当前业务量统计
     * @return
     */
    public void dayBusiness(){
        try {
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            SimpleDateFormat fmat=new SimpleDateFormat("yyyy-MM-dd");
            String start = sdf.format(DateUtil.getOnDutyTime());//上班时间8:30
            String end = sdf.format(DateUtil.getOffDutyTime());//下班时间18:00
            String dayEnd = fmat.format(DateUtil.getDay()) + " 23:59:59";
            int numDayTotal = statisticsService.getNumDayTotal(start,end);//取号总数
            int totalComplete = statisticsService.getTotalComplete(start,end);//已经办结
            int totalDoing = statisticsService.getTotalDoing(start,end);//正在办理
            int totalWaiting = statisticsService.getTotalWaiting(start,end);//当前等待
            //存入redis
            redisUtil.hashSet(DateUtil.format(new Date(),Constants.DAY),Constants.NUM_DAY_TATAL,numDayTotal);
            redisUtil.hashSet(DateUtil.format(new Date(),Constants.DAY),Constants.TOTAL_COMPLETE,totalComplete);
            redisUtil.hashSet(DateUtil.format(new Date(),Constants.DAY),Constants.TOTAL_DOING,totalDoing);
            redisUtil.hashSet(DateUtil.format(new Date(),Constants.DAY),Constants.TOTAL_WAITING,totalWaiting);
        }catch (Exception e) {
            logger.info("定时获取天数据异常:{}",e);
            //参考现场初始化公司本地展示数据
            //预约数据
            redisUtil.hashSet(DateUtil.format(new Date(),Constants.DAY),Constants.NUM_DAY_TATAL,86);
            redisUtil.hashSet(DateUtil.format(new Date(),Constants.DAY),Constants.TOTAL_COMPLETE,62);
            redisUtil.hashSet(DateUtil.format(new Date(),Constants.DAY),Constants.TOTAL_DOING,87);
            redisUtil.hashSet(DateUtil.format(new Date(),Constants.DAY),Constants.TOTAL_WAITING,91);
        }
    }

    //2.当天平均等待受理时间
    /**
     * 平均等待时间(分)、平均受理时间(分)、好评率
     */
    public void averageNumCron(){
        try {
            //获取月份数字
            int monthNum = DateUtil.getMonthNum();
            //计算工作日
            int notWorkDay = DateUtil.getNotWorkDay(1);
            Date yesterday = DateUtil.getLateDate("yyyy-MM-dd HH:mm:ss", 1 + notWorkDay);
            Date currentDay = DateUtil.getCurrentDay();
            //获取平均等待时长分钟
            Double wminutes = statisticsService.getWaitTime(yesterday,currentDay);
            if(wminutes == null) {
                //如果为null，那么用配置文件里面的初始化值
                wminutes = Double.parseDouble(waitTime);
            }else {
                wminutes = new BigDecimal(wminutes).setScale(2,BigDecimal.ROUND_DOWN).doubleValue();
            }
            //获取平均受理时长分钟
            Double aminutes = statisticsService.getAccessTime(yesterday,currentDay);
            if(aminutes == null) {
                //如果为null，那么用配置文件里面的初始化值
                aminutes = Double.parseDouble(accessTime);
            }else {
                aminutes = new BigDecimal(aminutes).setScale(2,BigDecimal.ROUND_DOWN).doubleValue();
            }
            //获取近1天好差评率
            Map<String,String> map = statisticsService.totalRate();
            String goodEvalRate = map.get("goodEvalRate");
            //统计平均等待时长
            redisUtil.hashSet(Constants.MONTH_AVERAGE_WAIT_NUM,monthNum+"",wminutes);
            //统计平均受理时长
            redisUtil.hashSet(Constants.MONTH_AVERAGE_ACCEPT_NUM,monthNum+"",aminutes);
            //统计好评率
//            redisUtil.hashSet(Constants.MONTH_GOOD_EVALUATE_NUM,monthNum+"", goodEvalRate);
            redisUtil.hashSet(Constants.MONTH_GOOD_EVALUATE_NUM,monthNum+"", "100%");

            //前天到昨天的平均等待时长
            Date dayBeforeYesterday = DateUtil.getLateDate("yyyy-MM-dd HH:mm:ss", 2 + notWorkDay);
            //获取平均等待时长分钟
            Double yesterdayWaitMinutes = statisticsService.getWaitTime(dayBeforeYesterday,yesterday);
            if(yesterdayWaitMinutes == null) {
                //如果为null，那么用配置文件里面的初始化值
                yesterdayWaitMinutes = Double.parseDouble(waitTime) + 1;
            }else {
                yesterdayWaitMinutes = new BigDecimal(yesterdayWaitMinutes).setScale(2,BigDecimal.ROUND_DOWN).doubleValue();
            }
            //获取平均受理时长分钟
            Double yesterdayAccessMinutes = statisticsService.getAccessTime(dayBeforeYesterday,yesterday);
            //是否打开平均受理模拟数据，0否，1是
            if(yesterdayAccessMinutes == null) {
                //如果为null，那么用配置文件里面的初始化值
                yesterdayAccessMinutes = Double.parseDouble(accessTime) + 1;
            }else {
                yesterdayAccessMinutes = new BigDecimal(yesterdayAccessMinutes).setScale(2,BigDecimal.ROUND_DOWN).doubleValue();
            }
            //统计平均等待时长
            redisUtil.hashSet(Constants.YESTERDAY_AVERAGE_WAIT_NUM,monthNum+"",yesterdayWaitMinutes);
            //统计平均受理时长
            redisUtil.hashSet(Constants.YESTERDAY_AVERAGE_ACCEPT_NUM,monthNum+"",yesterdayAccessMinutes);

        }catch (Exception e) {
            logger.info("获取近一日平均等待、平均受理时长、好评率异常："+e);
        }
    }

    //3.当天的各时段取号量
    public void dayAcceptNumInit() {
        try {
            //当天的每个时间端（取号数统计=人流量）
            //计算工作日
            Date today = DateUtil.getDay();
            Map<Object, Object> todayDateMap = new HashMap<Object, Object>();
            todayDateMap.put("8:30~9:30", statisticsService.lateComare(today, 8));
            todayDateMap.put("9:30~10:30", statisticsService.lateComare(today, 9));
            todayDateMap.put("10:30~11:30", statisticsService.lateComare(today, 10));
            todayDateMap.put("11:30~12:00", statisticsService.lateComare(today, 11));
            todayDateMap.put("14:30~15:30", statisticsService.lateComare(today, 14));
            todayDateMap.put("15:30~16:30", statisticsService.lateComare(today, 15));
            todayDateMap.put("16:30~17:30", statisticsService.lateComare(today, 16));
            redisUtil.hashSet(Constants.TODAY_PERSON_NUM, Constants.TODAYKEY_PERSON_NUM, todayDateMap);


            //上星期的同一天
            Calendar calStart = Calendar.getInstance();
            calStart.setTime(today);
            calStart.add(Calendar.DATE,-7);
            Date lastWeekStart1 = calStart.getTime();
            calStart.add(Calendar.DATE,-7);
            Date lastWeekStart2 = calStart.getTime();
            calStart.add(Calendar.DATE,-7);
            Date lastWeekStart3 = calStart.getTime();
            calStart.add(Calendar.DATE,-7);
            Date lastWeekStart4 = calStart.getTime();

            Calendar calEnd = Calendar.getInstance();
            calEnd.setTime(today);
            calEnd.add(Calendar.DATE,-6);
            Date lastWeekEnd1 = calEnd.getTime();
            calEnd.add(Calendar.DATE,-7);
            Date lastWeekEnd2 = calEnd.getTime();
            calEnd.add(Calendar.DATE,-7);
            Date lastWeekEnd3 = calEnd.getTime();
            calEnd.add(Calendar.DATE,-7);
            Date lastWeekEnd4 = calEnd.getTime();

            List<Integer> list8 = new ArrayList<>();
            list8.add(statisticsService.lateComareHistory(lastWeekStart1,lastWeekEnd1,8));
            list8.add(statisticsService.lateComareHistory(lastWeekStart2,lastWeekEnd2,8));
            /*list8.add(statisticsService.lateComareHistory(lastWeekStart3,lastWeekEnd3,8));
            list8.add(statisticsService.lateComareHistory(lastWeekStart4,lastWeekEnd4,8));*/
            Integer sumlist8 = 0;
            for (Integer i : list8) {
                sumlist8 += i;
            }
            List<Integer> list9 = new ArrayList<>();
            list9.add(statisticsService.lateComareHistory(lastWeekStart1,lastWeekEnd1,9));
            list9.add(statisticsService.lateComareHistory(lastWeekStart2,lastWeekEnd2,9));
            /*list9.add(statisticsService.lateComareHistory(lastWeekStart3,lastWeekEnd3,9));
            list9.add(statisticsService.lateComareHistory(lastWeekStart4,lastWeekEnd4,9));*/
            Integer sumlist9 = 0;
            for (Integer i : list9) {
                sumlist9 += i;
            }
            List<Integer> list10 = new ArrayList<>();
            list10.add(statisticsService.lateComareHistory(lastWeekStart1,lastWeekEnd1,10));
            list10.add(statisticsService.lateComareHistory(lastWeekStart2,lastWeekEnd2,10));
            /*list10.add(statisticsService.lateComareHistory(lastWeekStart3,lastWeekEnd3,10));
            list10.add(statisticsService.lateComareHistory(lastWeekStart4,lastWeekEnd4,10));*/
            Integer sumlist10 = 0;
            for (Integer i : list10) {
                sumlist10 += i;
            }
            List<Integer> list11 = new ArrayList<>();
            list11.add(statisticsService.lateComareHistory(lastWeekStart1,lastWeekEnd1,11));
            list11.add(statisticsService.lateComareHistory(lastWeekStart2,lastWeekEnd2,11));
            /*list11.add(statisticsService.lateComareHistory(lastWeekStart3,lastWeekEnd3,11));
            list11.add(statisticsService.lateComareHistory(lastWeekStart4,lastWeekEnd4,11));*/
            Integer sumlist11 = 0;
            for (Integer i : list11) {
                sumlist11 += i;
            }
            List<Integer> list14 = new ArrayList<>();
            list14.add(statisticsService.lateComareHistory(lastWeekStart1,lastWeekEnd1,14));
            list14.add(statisticsService.lateComareHistory(lastWeekStart2,lastWeekEnd2,14));
            /*list14.add(statisticsService.lateComareHistory(lastWeekStart3,lastWeekEnd3,14));
            list14.add(statisticsService.lateComareHistory(lastWeekStart4,lastWeekEnd4,14));*/
            Integer sumlist14 = 0;
            for (Integer i : list14) {
                sumlist14 += i;
            }
            List<Integer> list15 = new ArrayList<>();
            list15.add(statisticsService.lateComareHistory(lastWeekStart1,lastWeekEnd1,15));
            list15.add(statisticsService.lateComareHistory(lastWeekStart2,lastWeekEnd2,15));
            /*list15.add(statisticsService.lateComareHistory(lastWeekStart3,lastWeekEnd3,15));
            list15.add(statisticsService.lateComareHistory(lastWeekStart4,lastWeekEnd4,15));*/
            Integer sumlist15 = 0;
            for (Integer i : list15) {
                sumlist15 += i;
            }
            List<Integer> list16 = new ArrayList<>();
            list16.add(statisticsService.lateComareHistory(lastWeekStart1,lastWeekEnd1,16));
            list16.add(statisticsService.lateComareHistory(lastWeekStart2,lastWeekEnd2,16));
            /*list16.add(statisticsService.lateComareHistory(lastWeekStart3,lastWeekEnd3,16));
            list16.add(statisticsService.lateComareHistory(lastWeekStart4,lastWeekEnd4,16));*/
            Integer sumlist16 = 0;
            for (Integer i : list16) {
                sumlist16 += i;
            }

            Map<Object, Object> lastWeekTodayDateMap = new HashMap<Object, Object>();
            lastWeekTodayDateMap.put("8:30~9:30", sumlist8/2);
            lastWeekTodayDateMap.put("9:30~10:30", sumlist9/2);
            lastWeekTodayDateMap.put("10:30~11:30", sumlist10/2);
            lastWeekTodayDateMap.put("11:30~12:00", sumlist11/2);
            lastWeekTodayDateMap.put("14:30~15:30", sumlist14/2);
            lastWeekTodayDateMap.put("15:30~16:30", sumlist15/2);
            lastWeekTodayDateMap.put("16:30~17:30", sumlist16/2);
            redisUtil.hashSet(Constants.LASTWEEK_TODAY_PERSON_NUM, Constants.LASTWEEK_TODAYKEY_PERSON_NUM, lastWeekTodayDateMap);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 4.当天各业务区等待量/取号量TOP10
     */
    public void getTotalWaitingAndGetting() {
        try {
            List<WaitAndGetTotal> waitAndGetTotalList = statisticsService.getTotalWaitingAndGetting();
            redisUtil.hashSet(Constants.WAITING_GETTING_RATE, Constants.WAITING_GETTING_COUNT, waitAndGetTotalList);
        }catch (Exception e) {
            logger.info("各业务区排队量、取号量异常："+e);
        }
    }

    //5.近七天各渠道数据
    public void sevenDayChannelDataTotal() {
        try {
            Map<String, Integer> channelDataMap = statisticsService.sevenDayChannelDataTotal();
            redisUtil.hashSet(Constants.GET_TICK_CHANNEL_COUNT, Constants.GET_TICK_CHANNEL_COUNT_KEY, channelDataMap);
        }catch (Exception e) {
            logger.info("近七天各渠道数据异常："+e);
        }
    }

    //6.近七天各渠道申办量
    /**
     * 现场申办、网上申办、自助办
     */
    public void acceptWeekInit(){
        Map<String, String> map = statisticsService.getWeekBidType();
        redisUtil.hashSet(Constants.PACCEPT_WEEK_NUM,Constants.CACCEPT_WEEK_NUM,map);
    }

    //7.近七天文件柜存取件数量对比
    public void docLateTenReceiveTypeCron(){
        try {
            Map<String, Object> lateTenMap = statisticsService.lateTen();//最近10天放件人类型对比
            redisUtil.hashSet(Constants.PRECEIVE_TYPE_LATE_TEN,Constants.CRECEIVE_TYPE_LATE_TEN,lateTenMap);
        }catch (Exception e) {
            logger.info("获取文件柜放件人类型最近10天对比，工作人员、办事人员异常："+e);
        }
    }

    //8.近七天取票方式趋势图
    /**
     * 现场取号、预约取号
     */
    public void takeNumTypeNumCron(){
        try {
            Map<String, Integer> orderMap = statisticsService.totalLateOrder();//获取近7天预约取号数
            Map<String, Integer> currMap = statisticsService.totalLateCurrent();//获取近7天现场取号数
            //Map<String, Integer> wxMap = takeNumberService.totalLateWeiXin();//获取近7天微信取号数
            redisUtil.hashSet(Constants.PTAKE_NUM_TYPE,Constants.ORDER_NUM_TYPE,orderMap);
            redisUtil.hashSet(Constants.PTAKE_NUM_TYPE,Constants.CURR_NUM_TYPE,currMap);
            //redisUtil.hashSet(Constants.PTAKE_NUM_TYPE,Constants.WEIXIN_NUM_TYPE,wxMap);
        }catch (Exception e) {
            logger.info("获取取票方式数：现场取号、预约取号异常："+e);
        }
    }

    //9.每月各渠道业务受理量
    public void acceptMethodInit(){
        Map<String, Map<String, String>> map = statisticsService.getMonthBidType();
        redisUtil.hashSet(Constants.PACCEPT_METHOD_NUM,Constants.CACCEPT_METHOD_NUM,map);
    }

    //10.近30天按时办结统计
    public void finishRate(){
        try {
            Map<String, String> finishRate = statisticsService.finishRate();
            redisUtil.hashSet(Constants.FINISH_RATE, Constants.FINISH_COUNT, finishRate);
        }catch (Exception e) {
            logger.info("获取近30天办结率异常："+e);
        }
    }

    //11.近30天各业务区域申办量统计
    /**
     * 设置专区受理量--近30天各业务区域申办量统计
     */
    public void zoneAcceptNumCron(){
        try {
            Map<String, Integer> temp = new HashMap<>();
            Map<String, Integer> map = statisticsService.areaApplyTotal();
            if (map != null && map.size() != 0) {
                for (Map.Entry<String, Integer> m : map.entrySet()) {
                    temp.put(m.getKey(),m.getValue()+Integer.valueOf(redisUtil.get(Constants.BASE_ACCEPT_NUM)));
                }
            }
            redisUtil.hashSet(Constants.PZONE_ACCEPT_NUM,Constants.CZONE_ACCEPT_NUM,temp);
        }catch (Exception e) {
            logger.info("获取近30天热门业务区域业务量异常："+e);
        }
    }

    //12.近30天好差评率统计
    public void gbSatisfictionCron(){
        Map<String,String> map = statisticsService.totalRate();
        redisUtil.hashSet(Constants.PZONE_GOODS_BAD_SATISFICATION_NUM,Constants.CZONE_GOODS_BAD_SATISFICATION_NUM,map);
    }

    //13.近30天各业务区域好差评得分排名（满分5分）
    public void zoneSatisfictionCron(){
        try {
            Map<String,String> map = statisticsService.scoreEval();
            redisUtil.hashSet(Constants.PZONE_SATISFICATION_NUM,Constants.CZONE_SATISFICATION_NUM,map);
        }catch (Exception e) {
            logger.info("获取专区好评数异常："+e);
        }
    }

    /**
     * 14.各业务区等待与受理时间
     */
    public void getTotalWaitingAndGettingTimeForArea() {
        try {
            List<WaitAndGetTimeForArea> waitTimeForArea = statisticsService.getWaitTimeForArea();
            redisUtil.hashSet(Constants.WAITING_GETTING_TIME, Constants.WAITING_GETTING_TIME_COUNT, waitTimeForArea);
        }catch (Exception e) {
            logger.info("各业务区等待与受理时间异常："+e);
        }
    }

    //15.近30天业务申办量Top8
    public void topEightItemMonthCron(){
        int EightTask=8;//代表前8
        try {
            int notWorkDay = DateUtil.getNotWorkDay(30);
            //如果查询数据为空
            List<String> workDays = DateUtil.getThirtyDate();
            String start = workDays.get(workDays.size()-1) + " 00:00:00";
            Date late30Date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(start);
            List<TopEightTask> topEightTasks = statisticsService.topEightTask(late30Date);
            //List<TopEightTask> topEightTasks = statisticsService.topEightTask(DateUtil.getLateDate("yyyy-MM-dd HH:mm:ss",30 + notWorkDay));
            if (topEightTasks == null) {
                topEightTasks = new ArrayList<TopEightTask>();
                Map<String,String> map = redisUtil.hashGetP(Constants.ITEM_TOP_EIGHT);
                //设置前8事项的办理数
                for(String key: map.keySet()){
                    String value = map.get(key).toString();
                    TopEightTask topEightTask = new TopEightTask();
                    topEightTask.setNum(Integer.valueOf(value));
                    topEightTask.setTaskname(key);
                    topEightTasks.add(topEightTask);
                }
            }
            if (topEightTasks.size() != EightTask) {
                Map<String,String> map = redisUtil.hashGetP(Constants.ITEM_TOP_EIGHT);
                int index = EightTask - topEightTasks.size();
                for(String key: map.keySet()){
                    if(index!=0) {
                        String value = map.get(key).toString();
                        TopEightTask topEightTask = new TopEightTask();
                        topEightTask.setNum(Integer.valueOf(value));
                        topEightTask.setTaskname(key);
                        topEightTasks.add(topEightTask);
                        index--;
                    }else {
                        break;
                    }
                }
            }

            //对业务总量进行排序
            topEightTasks.sort(new Comparator<TopEightTask>() {
                @Override
                public int compare(TopEightTask o1, TopEightTask o2) {
                    return o2.getNum()-o1.getNum();
                }
            });

            redisUtil.hashSet(DateUtil.format(new Date(), Constants.MONTH), Constants.TOP_EIGHT_ITEM_MONTH, topEightTasks);
        }catch (Exception e){
            logger.info("获取前八事项异常"+e);
        }
    }

    //16.近30天业务量统计
    public void monthRunBatchByCron(){
        try {
            /*下面的都需要修改为30工作日，不算今天*/
            List<String> workDays = DateUtil.near30WorkDay();
            String start = workDays.get(0) + " 00:00:00";
            String end = workDays.get(workDays.size() - 1) + " 23:59:59";
            Integer currentMonthTotal = statisticsService.getXCNumMouthTotal(start, end);//获取月现场取号数
            Integer orderMonthTotal = statisticsService.getYYNumMouthTotal(start, end);//获取月预约取号数
            Integer monthOrderTotal = statisticsService.getOrderMouthTotal(start, end);//获取当月预约数
            Integer monthNumTotal = statisticsService.getNumMouthTotal(start, end);//获取当月的取号总数
            Integer webchatMonthTotal = statisticsService.getWXNumMouthTotal(start,end);//获取当月的微信取号总数
            Integer receiveMonthTotal = statisticsService.getMouthTotalDeal(start,end);//近30天收件总数
            Integer totalSendMonth = statisticsService.getMouthTotalSend(start, end);//近30天发证总数
            redisUtil.hashSet(DateUtil.format(new Date(),Constants.MONTH),Constants.NUM_MONTH_TATAL,monthNumTotal);
            redisUtil.hashSet(DateUtil.format(new Date(),Constants.MONTH),Constants.ORDER_MONTH_TATAL,monthOrderTotal);
            redisUtil.hashSet(DateUtil.format(new Date(),Constants.MONTH),Constants.NUM_XC_MONTH_TATAL,currentMonthTotal);
            redisUtil.hashSet(DateUtil.format(new Date(),Constants.MONTH),Constants.NUM_YY_MONTH_TATAL,orderMonthTotal);
            redisUtil.hashSet(DateUtil.format(new Date(),Constants.MONTH),Constants.NUM_SEND_MONTH_TATAL,totalSendMonth);
            redisUtil.hashSet(DateUtil.format(new Date(),Constants.MONTH),Constants.NUM_RECEIVE_MONTH_TATAL,receiveMonthTotal);
            redisUtil.hashSet(DateUtil.format(new Date(),Constants.MONTH),Constants.NUM_WX_MONTH_TATAL,webchatMonthTotal);//月预约数
        }catch (Exception e) {
            logger.info("定时获取月数据异常:{}",e);
            redisUtil.hashSet(DateUtil.format(new Date(),Constants.MONTH),Constants.NUM_MONTH_TATAL,528);
            redisUtil.hashSet(DateUtil.format(new Date(),Constants.MONTH),Constants.ORDER_MONTH_TATAL,333);
            redisUtil.hashSet(DateUtil.format(new Date(),Constants.MONTH),Constants.NUM_XC_MONTH_TATAL,208);
            redisUtil.hashSet(DateUtil.format(new Date(),Constants.MONTH),Constants.NUM_YY_MONTH_TATAL,320);
            redisUtil.hashSet(DateUtil.format(new Date(),Constants.MONTH),Constants.NUM_SEND_MONTH_TATAL,198);
            redisUtil.hashSet(DateUtil.format(new Date(),Constants.MONTH),Constants.NUM_RECEIVE_MONTH_TATAL,528);
            redisUtil.hashSet(DateUtil.format(new Date(),Constants.MONTH),Constants.NUM_WX_MONTH_TATAL,123);//月预约数
        }
    }

    //16.1 近30天业务量统计
    //最近30天每天的收件量和发证量统计，用于30天坐标图
    public void late30RunBatchByCron(){
        try {
            //最近30天的收件量
            Map<String, Integer> lateReceiveNumMap = statisticsService.lateThirty(30);
            redisUtil.hashSet(Constants.LATELY_30,Constants.LATELY30_RECEIVE_NUM,lateReceiveNumMap);
            //最近30天的发证量
            Map<String, Integer> lateSendNumMap = statisticsService.lateThirtySend(30);
            redisUtil.hashSet(Constants.LATELY_30,Constants.LATELY30_SEND_NUM,lateSendNumMap);
        }catch (Exception e) {
            logger.info("定时获取最近30天收发件量数据异常:{}",e);
        }
    }

    //获取最近7天30天的人流对比
    public void latelyAcceptNumCron() {
        Random r = new Random();
        // 是否打开模拟数据，0否，1是
        String openSimulateData = systemParamService.getValueByName("openSimulateData");
        //logger.info("是否打开模拟数据，0否，1是，openSimulateData=" + openSimulateData);
        if (StringUtils.isNotBlank(openSimulateData) && "1".equals(openSimulateData)) {
            Map<Object, Object> late30DateMap = new HashMap<Object, Object>();
            late30DateMap.put("8:30~9:30", (r.nextInt(35)+30)*30);
            late30DateMap.put("9:30~10:30", (r.nextInt(40)+40)*30);
            late30DateMap.put("10:30~11:30", (r.nextInt(35)+45)*30);
            late30DateMap.put("11:30~12:00", (r.nextInt(25)+10)*30);
            late30DateMap.put("14:30~15:30", (r.nextInt(30)+70)*30);
            late30DateMap.put("15:30~16:30", (r.nextInt(40)+40)*30);
            late30DateMap.put("16:30~17:30", (r.nextInt(30)+30)*30);
            Map<Object, Object> late7DateMap = new HashMap<Object, Object>();
            late7DateMap.put("8:30~9:30", (r.nextInt(35)+30)*10);
            late7DateMap.put("9:30~10:30", (r.nextInt(40)+40)*10);
            late7DateMap.put("10:30~11:30", (r.nextInt(35)+45)*10);
            late7DateMap.put("11:30~12:00", (r.nextInt(25)+10)*10);
            late7DateMap.put("14:30~15:30", (r.nextInt(30)+70)*10);
            late7DateMap.put("15:30~16:30", (r.nextInt(40)+40)*10);
            late7DateMap.put("16:30~17:30", (r.nextInt(30)+30)*10);
            redisUtil.hashSet(Constants.LATELY_PERSON_NUM, Constants.LATELY30_PERSON_NUM, late30DateMap);
            redisUtil.hashSet(Constants.LATELY_PERSON_NUM, Constants.LATELY7_PERSON_NUM, late7DateMap);
        } else {
            try {
                //最近30天的每个时间端（取号数统计=人流量）
                //计算工作日
                /*int notWorkDay = DateUtil.getNotWorkDay(30);
                Date late30Date = DateUtil.getLateDate("yyyy-MM-dd HH:mm:ss", 30 + notWorkDay);*/
                List<String> workDays = DateUtil.near30WorkDay();
                String start = workDays.get(0) + " 00:00:00";
                Date late30Date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(start);
                Map<Object,Object> late30DateMap = new HashMap<Object,Object>();
                late30DateMap.put("8:30~9:30",statisticsService.lateComare(late30Date,8));
                late30DateMap.put("9:30~10:30",statisticsService.lateComare(late30Date,9));
                late30DateMap.put("10:30~11:30",statisticsService.lateComare(late30Date,10));
                late30DateMap.put("11:30~12:00",statisticsService.lateComare(late30Date,11));
                late30DateMap.put("14:30~15:30",statisticsService.lateComare(late30Date,14));
                late30DateMap.put("15:30~16:30",statisticsService.lateComare(late30Date,15));
                late30DateMap.put("16:30~17:30",statisticsService.lateComare(late30Date,16));
                //最近7天的每个时间端（取号数统计=人流量）
                //计算工作日
                /*int notWork7Day = DateUtil.getNotWorkDay(7);
                Date late7Date = DateUtil.getLateDate("yyyy-MM-dd HH:mm:ss", 7 + notWork7Day);*/
                List<String> workSevenDays = DateUtil.near7WorkDay();
                String startDay = workSevenDays.get(0) + " 00:00:00";
                Date late7Date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(startDay);
                Map<Object,Object> late7DateMap = new HashMap<Object,Object>();
                late7DateMap.put("8:30~9:30",statisticsService.lateComare(late7Date,8));
                late7DateMap.put("9:30~10:30",statisticsService.lateComare(late7Date,9));
                late7DateMap.put("10:30~11:30",statisticsService.lateComare(late7Date,10));
                late7DateMap.put("11:30~12:00",statisticsService.lateComare(late7Date,11));
                late7DateMap.put("14:30~15:30",statisticsService.lateComare(late7Date,14));
                late7DateMap.put("15:30~16:30",statisticsService.lateComare(late7Date,15));
                late7DateMap.put("16:30~17:30",statisticsService.lateComare(late7Date,16));
                redisUtil.hashSet(Constants.LATELY_PERSON_NUM,Constants.LATELY30_PERSON_NUM,late30DateMap);
                redisUtil.hashSet(Constants.LATELY_PERSON_NUM,Constants.LATELY7_PERSON_NUM,late7DateMap);
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    //事项同源统计，是否本地化事项
    public void localRate() {
        Map<String, String> localRateMap = statisticsService.localRate();
        redisUtil.hashSet(Constants.LOCAL_RATE,Constants.LOCAL_COUNT,localRateMap);
    }

    //近30天退件率
    public void sendBackRate(){
        try {
            Map<String, String> sendBackRateMap = statisticsService.sendBackRate();
            redisUtil.hashSet(Constants.SENDBACK_RATE, Constants.SENDBACK_COUNT, sendBackRateMap);
        }catch (Exception e) {
            logger.info("获取近30天退件率异常："+e);
        }
    }

    /**
     * 每1分钟15秒执行一次
     */
    @Scheduled(cron = "${schedules.runEvery1Minu}")
    @Async
    public void runEvery1Minu() {
       try {
           dayRunBatchByCron();//0.当天业务量统计分析
           dayBusiness();//1.获取当前业务量统计
           averageNumCron();//2.当天平均等待受理时间
           dayAcceptNumInit();//3.当天的各时段取号量
           getTotalWaitingAndGetting();//4.当天各业务区等待量/取号量TOP10
           getTotalWaitingAndGettingTimeForArea();//14.各业务区等待与受理时间
           logger.info("runEvery1Minu");
       }catch(Exception e) {
           logger.info("runEvery1Minu:{}",e);
       }
    }

    /**
     * 每30分钟执行一次
     */
    @Scheduled(cron = "${schedules.runEvery30Minu}")
    @Async
    public void runEvery30Minu() {
        try {
            logger.info("runEvery30Minu");
        }catch(Exception e) {
            logger.info("runEvery30Minu:{}",e);
        }
    }

    /**
     * 每天凌晨1点执行一次
     */
    @Scheduled(cron = "${schedules.runEveryDay}")
    @Async
    public void runEveryDay() {
        try {
            sevenDayChannelDataTotal();//5.近七天各渠道数据
            acceptWeekInit();//6.近七天各渠道申办量
            docLateTenReceiveTypeCron();//7.近七天文件柜存取件数量对比
            takeNumTypeNumCron();//8.近七天取票方式趋势图
            acceptMethodInit();//9.每月各渠道业务受理量
            finishRate();//10.近30天按时办结统计
            zoneAcceptNumCron();//11.近30天各业务区域申办量统计
            gbSatisfictionCron();//12.近30天好差评率统计
            zoneSatisfictionCron();//13.近30天各业务区域好差评得分排名（满分5分）
            topEightItemMonthCron();//15.近30天业务申办量Top8
            monthRunBatchByCron();//16.近30天业务量统计
            late30RunBatchByCron();//16.1 近30天业务量统计
            latelyAcceptNumCron();//获取最近7天30天的人流对比
            localRate();//事项同源统计，是否本地化事项
            sendBackRate();//近30天退件率
            logger.info("runEveryDay");
        }catch(Exception e) {
            logger.info("runEveryDay:{}",e);
        }
    }
}
